const [isLoggedIn, userInfo,sessionId] = [Symbol(), Symbol(),Symbol()];
class UserSerivce {
    constructor ($state,$http, $q, $rootScope,$cookies,Constant, Event, AjaxError,ResponseService,Logger,Http) {
        Object.assign(this, {$state,$http, $q, $rootScope,$cookies,Constant, Event, AjaxError,ResponseService,Logger,Http});
        // private variable
        this[isLoggedIn] = false;
        this[userInfo] = null;
        this[sessionId] = null;
        console.log("urlPrefix: "+this.Constant.urlPrefix);
    }

    isLoggedIn () {
        return this[isLoggedIn];
    }

    /**
     * 根据账号获取密码问题
     * @param param
     */
    forget_pwd_question(param){
        let self =this;
        return self.Http.post("api/forget_pwd_question", param);
    }

    /**
     * 变更忘记的密码问题
     * @param param
     */
    forget_pwd(param){
        let self =this;
        return self.Http.post("api/forget_pwd", param);
    }

    checkLoggedInStatus () {
        const self = this;
        return this.$http.get(self.Constant.urlPrefix + 'api/user/loginstatus')
            .then(_success)
            .catch(_error);

        function _success (response) {
            const data = response.data;
            if (response.status === 200 && data.code === 0) {
                self._setUser(data.user_data);
                self.$rootScope.$broadcast(self.Event.AUTH_SESSION_VALID, data.user_data);
                return data.user_data;
            }
            return self.$q.reject(data.message);
        }

        function _error (reason) {
            self._clearUser();
            return self.AjaxError.catcher(reason);
        }
    }

    login (username, password) {
        const self = this;
        const req = {
            username,
            password
        };
        return this.$http.post(self.Constant.urlPrefix + 'api/login', req)
            .then(_success)
            .catch(_error);

        function _success (response) {
            const data = response.data;
            self.Logger.debug(response);
            if (response.status === 200 && data.ret_flag ==true) {
                self._setSessionId(data.session_id);
                self._setUser(data.user_data);
                self.$rootScope.$broadcast(self.Event.AUTH_LOGIN, data.user_data);
                return data.user_data;
            }else{
                layer.alert(data.ret_msg,{
                    title:"错误",
                    icon: 2,
                    btn:["知道了"],
                    btn1:function (index,layerro) {
                        layer.close(index);
                    }
                });
                return self.$q.reject(response);
            }
        }

        function _error (response) {
            layer.alert(response.data.message.content,{
                title:"错误",
                icon: 2,
                btn:["知道了"],
                btn1:function (index,layerro) {
                    layer.close(index);
                }
            });
            self._clearUser();
            return self.AjaxError.catcher(response);
        }
    }

    logout () {
        let self = this;
        return this.$http.post(self.Constant.urlPrefix + 'api/logout',{})
            .then(_success)
            .catch(_error);

        function _success (response) {
            const data = response.data;
            if (response.status === 200
                //&& response.success==true
              ) {
                self._clearUser();
                self.$rootScope.$broadcast(self.Event.AUTH_LOGOUT);
                self.$state.go("login");
            } else {
                return self.$q.reject(data.message);
            }
        }

        function _error (reason) {
            // log out user even API is failed
            self._clearUser();
            return self.AjaxError.catcher(reason);
        }
    }

    getUserInfo () {
        return this[userInfo];
    }

    getProductSummary () {
        const self = this;
        return this.$http.get(self.Constant.urlPrefix + 'api/user/products')
            .then(_success)
            .catch(this.AjaxError.catcher.bind(this.AjaxError));

        function _success (response) {
            const data = response.data;
            if (response.status === 200 && data.code === 0) {
                return data.result.summary;
            }
            return self.$q.reject(data.message);
        }
    }

    _setUser (userData) {
        this[isLoggedIn] = true;
        this[userInfo] = userData;
        this.$cookies.putObject("userData",userData);
    }

    getUser () {
        if(this[userInfo]){
            return this[userInfo] ;
        }else{
          let userData = this.$cookies.getObject("userData");
          if(userData){
              this[userInfo] = userData;
              this[isLoggedIn] = true;
              return userData;
          }else{
              this.$state.go("login");
          }
        }
    }

    _clearUser () {
        this[isLoggedIn] = false;
        this[userInfo] = null;
        this[sessionId]=null;
        this.$cookies.remove("userData");
    }
    _setSessionId(sessionId){
        this[sessionId] = sessionId;
        this.$cookies.put("sessionId",sessionId);
        sessionStorage.setItem('sessionId', sessionId);
    }

    /**
     * 获取购买记录
     *
     * {
        "page_index": 2, //页码
        "page_size": 10,   //分页大小
        "lot_id": 31, //彩种代码,-9全部,彩种列表可以通过公共方法“get_lottery_type”获取
        "status": -9, 	//状态，-9全部，0已撤单，1待付款，2处理中，3出票中，4下单成功，5下单失败，6部份成功
        "start_date": "2019-08-16",  //查询开始日期
        "end_date": "2019-09-16"  //查询结束日期
    }
     */
    getOrderList(param){
        let self = this;
        return self.Http.post("api/get_order_list", param);
    }

    /**
     * 查询中奖记录
     * @param param
     *     {
        "page_index": 2,  //页码
        "page_size": 10, //分页大小
        "lot_id": 31,   //彩种代码,-9全部,彩种列表可以通过公共方法“get_lottery_type”获取
        "status": -9, //状态，-9全部，0已撤单，1待付款，2处理中，3出票中，4下单成功，5下单失败，6部份成功
        "start_date": "2019-08-16", //查询开始日期
        "end_date": "2019-09-16" //查询结束日期
    }
     */
    getAwardList(param){
        let self = this;
        return self.Http.post("api/get_award_list", param);
    }

    /**
     *查询资金明细
     * @param param
     *     {
        "page_index": 2,  //页码
        "page_size": 10,  //分页大小
        "trade_type": -1, 	//交易类型：1:充值，2银行转账，3撤单返款，4奖金派发，5其它收入，11购买彩票，12退款，19其它支出
        "start_date": "2019-08-16", //查询开始日期
        "end_date": "2019-09-16" //查询结束日期
    }
     */
    getFundDetailList(param){
        let self = this;
        return self.Http.post("api/get_fund_detail_list", param);
    }

    /**
     * 修改密码
     * @param param
     *     {
        "curr_pwd": "123456",  //当前密码
        "new_pwd": "123456", //新密码
        "confirm_new_pwd": "123456"//确认新密码
    }
     */
    updatePwd(param){
        let self = this;
        return self.Http.post("api/update_pwd", param);
    }

    /**
     *  提现申请
     * @param param
     *     {
        "cash_amount": "1000.00",    //提现金额
        "cash_pwd": "123456"         //提现密码
    }
     */
    applyCash(param){
        let self = this;
        return self.Http.post("api/cash_apply", param);
    }

    /**
     * 绑定提现账号
     * {
        "cash_type": 2,                             //提现方式： 1网银,2支付宝,3微信
        "cash_account": "2012423892898923892",      //提现账号(网银、支付宝、微信账号)
        "user_name": "张三",                          //提现银行姓名(如果选择网银则必须传入该字段)
        "bank_name": "招商银行",                    //提现银行卡名称(如果选择网银则必须传入该字段), 下拉列表选择
        "bank_branch": "上海浦东支行",            //填写支行
        "cash_pwd": "123456"                          //提现密码
    }
     */
    bindAccountCash(param){
        let self = this;
        return self.Http.post("api/cash_account_bind", param);
    }

    /**
     * 查询提现记录
     * @param param
     *
     *     {
        "page_index": 2,     //页码
        "page_size": 10,     //分页大小
        "start_date": "2019-08-16",     //查询开始日期
        "end_date": "2019-09-16",       //查询结束日期
        "cash_status": 1            	//提现状态：0未提现，1已提现
    }
     */
    getCashList(param){
        let self = this;
        return self.Http.post("api/get_cash_list", param);
    }

    register(param){
        let self = this;
        return self.Http.post("api/reg", param);
    }

    getQuestionList(){
        let self = this;
        return self.Http.post("api/get_question_list", {});
    }



}

UserSerivce.$inject = ["$state",'$http', '$q', '$rootScope',"$cookies","Constant", 'Event', 'AjaxErrorHandler',"ResponseService","Logger","Http"];

export default UserSerivce;
